package com.iiot;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 支持连接池的 HTTP 客户端工具类
 * 用于持久化 HTTP 连接，提高并发效率
 */
public class HttpPersistent {

    private CloseableHttpClient httpClient;
    private PoolingHttpClientConnectionManager connManager;

    /**
     * 启动连接池
     *
     * @param maxTotal    最大连接数
     * @param maxPerRoute 每个路由最大连接数
     */
    public void start(int maxTotal, int maxPerRoute) {
        connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(maxTotal);           // 总连接数
        connManager.setDefaultMaxPerRoute(maxPerRoute); // 每个路由最大连接数

        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000)        // 连接超时 5s
                .setSocketTimeout(5000)         // 读取超时 5s
                .setConnectionRequestTimeout(3000) // 从连接池获取连接超时
                .build();

        httpClient = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(config).build();
    }

    /**
     * 执行 HTTP GET 请求，支持自定义超时（单位：秒）
     *
     * @param url     请求地址
     * @param timeout 超时时间（秒）
     * @return 响应字节数组
     * @throws Exception 请求失败或超时
     */
    public byte[] doHttpGet(String url, int timeout) throws Exception {
        if (httpClient == null) {
            throw new IllegalStateException("HttpPersistent not started. Call start() first.");
        }

        // 动态设置超时（覆盖默认）
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(config);

        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toByteArray(entity);
            } else {
                throw new IOException("Empty response entity");
            }
        } catch (Exception e) {
            httpGet.abort(); // 确保释放连接
            throw e;
        }
    }

    /**
     * 关闭连接池（可选，用于优雅关闭）
     */
    public void shutdown() {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (connManager != null) {
            connManager.shutdown();
        }
    }
}